﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Frame.Lib.Common;
using Frame.Lib.Core.Log;

namespace Frame.Lib.Web
{
    public class FrameModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication Application)
        {
            Application.BeginRequest += new EventHandler(Application_BeginRequest);

            Application.Error += new EventHandler(Application_Error);
        }


        void Application_Error(object sender, EventArgs e)
        {
            if (!AppSetting.IsDebug)
            {
                HttpContext context = ((HttpApplication)sender).Context;
                string returnUrl = context.Request.Path;


                Exception ex = context.Server.GetLastError().InnerException == null ? context.Server.GetLastError() : context.Server.GetLastError().InnerException;
                try
                {
                    Logger.Exception(ex, "Application Error");
                }
                catch
                {
                }

                string errorMessage = ex.Message;

                errorMessage = errorMessage.Replace("\r\n", "");
                errorMessage = errorMessage.Replace(@"""", "");
                errorMessage = errorMessage.Replace(@"'", "");
                errorMessage = errorMessage.Replace("<", "&lt;");
                errorMessage = errorMessage.Replace(">", "&gt;");

                //防止循环重定向
                if (!context.Request.RawUrl.ToLower().Contains("error.aspx"))
                {
                    string url = string.Format("{0}error.aspx?ErrorMessage={1}&ReturnUrl={2}", GlobalVar.WebAppPath, context.Server.UrlEncode(errorMessage), context.Server.UrlEncode(returnUrl));
                    context.Response.Redirect(url, true);
                }
            }
        }


        void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;

            //context.RewritePath(

        }



        #endregion
    }
}
